<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/28 14:36
 * Desc: 会员三方信息
 */
class Model_Api_V2_Member_Third extends ORM
{

    /**
     * 更新多余的会员账号
     * @param $mid
     * @param $third_id
     * @param $union_id
     * @return void
     */
    public static function update_redundant_by_unionid($mid, $third_id, $union_id)
    {
        //更改openId
        DB::update('member_third')
            ->set(array('openid' => $union_id))
            ->where('id', '=', $third_id)
            ->execute();

        //整理多余用户
        $rich_user = DB::select()
            ->from('member_third')
            ->where('openid', '=', $union_id)
            ->and_where('id', '<>', $third_id)
            ->execute()
            ->current();

        if ($rich_user) {
            // 删除多余的三方信息
            DB::delete('member_third')
                ->where('id', '=', $rich_user['id'])
                ->execute();
            // 删除多余的会员账号
            DB::delete('member')
                ->where('mid', '=', $rich_user['mid'])
                ->execute();
            // 更新会员订单id
            DB::update('member_order')
                ->set(array('memberid' => $mid))
                ->where('memberid', '=', $rich_user['mid'])
                ->execute();
        }
    }

    /**
     * 通过 openid 和 union_id 获取会员三方信息
     * @param $openid
     * @param string $union_id
     * @return mixed|null
     * @throws Kohana_Exception
     */
    public static function get_member_third_by_wx($openid, string $union_id = '')
    {
        if ($union_id) {
            $member_third1 = DB::select()
                ->from('member_third')
                ->where('openid', '=', $union_id);
        }
        $builder = DB::select()
            ->from('member_third')
            ->where('wx_openid', '=', $openid);
        if (isset($member_third1)) {
            $builder->union($member_third1);
        }
        return $builder->execute()->current();
    }
}